<template>
  <el-dialog
    title="角色授权管理"
    v-model="dialogVisible"
    width="70%"
    destroy-on-close
       :modal="true"
    :append-to-body="true"
    :lock-scroll="true"
    class="role-access-dialog"
  >
    <div class="role-access-container" v-loading="loading">
      <div class="operation-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索角色"
          clearable
          style="width: 250px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <div class="buttons">
          <el-button type="primary" @click="showGrantDialog">
            <el-icon><Document /></el-icon> 授予权限
          </el-button>
          <el-button @click="refreshRoleList">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
        </div>
      </div>

      <el-table
        :data="filteredRoles"
        border
        style="width: 100%"
        height="calc(100% - 80px)"
      >
        <el-table-column prop="id" label="角色ID" width="120"></el-table-column>
        <el-table-column prop="name" label="角色名称" width="180"></el-table-column>
        <el-table-column prop="description" label="描述" min-width="320"></el-table-column>

        <el-table-column label="授权时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.access?.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="过期时间" width="180">
          <template #default="scope">
            <span v-if="scope.row.access?.expires_at">
              {{ formatDate(scope.row.access.expires_at) }}
            </span>
            <el-tag v-else type="success">永久有效</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              type="danger"
              link
              @click="handleRevokeAccess(scope.row)"
              :disabled="!scope.row.access"
            >
              <el-icon><Delete /></el-icon> 撤销权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 授权对话框 -->
    <el-dialog
      v-model="grantDialogVisible"
      title="授予数据集访问权限"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <el-form :model="grantForm" label-width="100px" :rules="grantRules" ref="grantFormRef">
        <el-form-item label="角色列表" prop="role_ids">
          <el-select
            v-model="grantForm.role_ids"
            multiple
            filterable
            remote
            placeholder="请输入角色名称搜索"
            :remote-method="searchRoles"
            :loading="roleSearchLoading"
            style="width: 100%"
            @focus="handleRoleSelectFocus"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="过期时间" prop="expires_at">
          <el-date-picker
            v-model="grantForm.expires_at"
            type="datetime"
            placeholder="选择过期时间（可选）"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
            clearable
          ></el-date-picker>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="grantDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleGrantAccess" :loading="grantLoading">确定</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, watch, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Delete, Document } from '@element-plus/icons-vue'
import { getRoleList } from '@/api/role'
import { getDatasetRoles, revokeRoleDatasetAccess, batchGrantRoleDatasetAccess } from '@/api/roleDataset'

const props = defineProps({
  modelValue: Boolean,
  datasetId: [String, Number]
})

const emit = defineEmits(['update:modelValue'])

// 对话框可见性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 状态
const loading = ref(false)
const roleList = ref([])
const searchKeyword = ref('')

// 授权对话框
const grantDialogVisible = ref(false)
const grantLoading = ref(false)
const grantForm = reactive({
  role_ids: [],
  dataset_ids: [],
  expires_at: null
})
const grantFormRef = ref(null)
const grantRules = {
  role_ids: [{ required: true, message: '请选择至少一个角色', trigger: 'change' }]
}

// 角色搜索相关
const roleSearchLoading = ref(false)
const roleOptions = ref([])

// 过滤角色列表
const filteredRoles = computed(() => {
  if (!searchKeyword.value) {
    return roleList.value
  }
  const keyword = searchKeyword.value.toLowerCase()
  return roleList.value.filter(role =>
    (role.name && role.name.toLowerCase().includes(keyword)) ||
    (role.description && role.description.toLowerCase().includes(keyword))
  )
})

// 获取角色列表
const fetchRoleList = async () => {
  if (!props.datasetId) return

  loading.value = true
  try {
    const res = await getDatasetRoles(props.datasetId)
    if (res && Array.isArray(res.data)) {
      roleList.value = res.data
    } else {
      roleList.value = []
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 刷新角色列表
const refreshRoleList = () => {
  fetchRoleList()
}

// 显示授权对话框
const showGrantDialog = () => {
  grantForm.dataset_ids = [props.datasetId]
  grantForm.role_ids = []
  grantForm.expires_at = null
  grantDialogVisible.value = true
}

// 搜索角色
const searchRoles = async (query) => {
  if (query.length < 2) return
  roleSearchLoading.value = true
  try {
    const res = await getRoleList({ search: query, limit: 20 })
    if (res && res.items) {
      roleOptions.value = res.items
    }
  } catch (error) {
    console.error('搜索角色失败:', error)
  } finally {
    roleSearchLoading.value = false
  }
}

// 处理角色选择框获得焦点
const handleRoleSelectFocus = async () => {
  if (roleOptions.value.length === 0) {
    roleSearchLoading.value = true
    try {
      const res = await getRoleList({ limit: 100 })
      if (res && res.items) {
        roleOptions.value = res.items
      }
    } catch (error) {
      console.error('获取角色列表失败:', error)
      ElMessage.error('获取角色列表失败: ' + (error.message || '未知错误'))
    } finally {
      roleSearchLoading.value = false
    }
  }
}

// 授予权限
const handleGrantAccess = async () => {
  if (!grantFormRef.value) return

  await grantFormRef.value.validate(async (valid) => {
    if (!valid) return

    grantLoading.value = true
    try {
      await batchGrantRoleDatasetAccess({
        role_ids: grantForm.role_ids,
        dataset_ids: grantForm.dataset_ids,
        expires_at: grantForm.expires_at
      })
      ElMessage.success('授权成功')
      grantDialogVisible.value = false
      fetchRoleList()
    } catch (error) {
      console.error('授权失败:', error)
      ElMessage.error('授权失败: ' + (error.message || '未知错误'))
    } finally {
      grantLoading.value = false
    }
  })
}

// 撤销权限
const handleRevokeAccess = (role) => {
  if (!role.access || !role.access.id) {
    ElMessage.warning('无法撤销，未找到授权记录')
    return
  }

  ElMessageBox.confirm(
    `确定要撤销角色 ${role.name} 对该数据集的访问权限吗？`,
    '撤销确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        await revokeRoleDatasetAccess(role.access.id)
        ElMessage.success('已成功撤销访问权限')
        fetchRoleList()
      } catch (error) {
        console.error('撤销权限失败:', error)
        ElMessage.error('撤销权限失败: ' + (error.message || '未知错误'))
      }
    })
    .catch(() => {
      // 用户取消操作
    })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch {
    return dateString
  }
}

// 监听datasetId变化
watch(() => props.datasetId, (newVal) => {
  if (newVal && dialogVisible.value) {
    fetchRoleList()
  }
})

// 监听对话框可见性变化
watch(dialogVisible, (newVal) => {
  if (newVal && props.datasetId) {
    fetchRoleList()
  }
})

// 组件挂载时获取角色列表
onMounted(() => {
  if (props.datasetId && dialogVisible.value) {
    fetchRoleList()
  }
})
</script>

<style scoped>
.role-access-dialog :deep(.el-dialog__body) {
  padding: 0;
  height: calc(80vh - 120px);
}

.role-access-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 15px;
}

.operation-bar {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.buttons {
  display: flex;
  gap: 10px;
}
</style>
